package cc.rengu.redp.bizimpl.utils;

import cc.rengu.redp.bizimpl.constant.UpmpConstant;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.SecureRandom;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class RSAEncrypt {

    public static void main(String[] args) throws Exception {
        String s = "haha123";
        Map<String, String> map = RSAEncrypt.genKeyPair();
        String s2 = RSAEncrypt.encrypt(s, map.get(UpmpConstant.KEY_PAIR_MAP_PUBLIC_KEY));
        String priKey = RSAEncrypt.encrypt(s, map.get(UpmpConstant.KEY_PAIR_MAP_PRIVATE_KEY));
        System.out.println("公钥加密后：" + s2);
        System.out.println("公钥解密后：" + RSAEncrypt.decrypt(s2, map.get(UpmpConstant.KEY_PAIR_MAP_PRIVATE_KEY)));
        System.out.println("公钥：" +  map.get(UpmpConstant.KEY_PAIR_MAP_PUBLIC_KEY));
        System.out.println("私钥：" +  map.get(UpmpConstant.KEY_PAIR_MAP_PRIVATE_KEY));

//        "公钥：MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC3eBKmDUPOqT3j6EQa2Ac/xRXFA2rzGABOQHt+T13WP9kN05yDp4FIvYf7w3jGg82mcYgdFHOg9EnHEGK3niUB9yXr5HG/3pVhBOPr4/KP1ICJreWV5GE1H1cP8CZZJnEc9IuiGeHhuG4LMtQVphDLOwNZOYyrm5PX8f9528dNAwIDAQAB";
//        "私钥：MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBALd4EqYNQ86pPePoRBrYBz/FFcUDavMYAE5Ae35PXdY/2Q3TnIOngUi9h/vDeMaDzaZxiB0Uc6D0SccQYreeJQH3Jevkcb/elWEE4+vj8o/UgImt5ZXkYTUfVw/wJlkmcRz0i6IZ4eG4bgsy1BWmEMs7A1k5jKubk9fx/3nbx00DAgMBAAECgYAiYVzVQx0Wx/4yDB9fDGZnW85VietrvG6qO0kpBURnVrWc8q+cuDHw6Jtn4Vxrjt1luFayZFe6rKx6oiZtlDQI1dYLpoedXN1wDqZ0Y+nip6WDotbwhprO03vbgROnTkz9m6yGM+LeSbMcWlwDRjeHT9rQJuLm7eWPW2AP6a0WKQJBAOgiKYvW55OyWzrBYhq1WWnlZabSs555qEbycxuNTFEQFCdPFubzTx56zs0rmKOiEbv6J52eag/63DelFaYKVi8CQQDKVQua4xi8ZKPGCeCj8PhECfKt/X00QzKUVwrqVguwH1pgQUc21Bh6cdk/W55racCeB7aw8QhEUU/sT3ETrVVtAkAxNnzkXq09zMQ2kqT/0I6iOrXwRh86a8RXNjNdFfml/ein5MaQM+kEJzkMmj+EAWoNFh2r9te5h4+EZIVQbESVAkALKrBuRvRZiXBkgK0OP0Fkd+wV4DSlysOi3j7y+fbBLKnPQCsPApurPldQIN1Ybki8MA7MKzFam+Y+U5AZFurtAkAaGxWSvNEWSrNCmJxSwigv4yOeWPwKMpaT75tRXBSpCR9Al5rRTszZuDV7cJZ59SsgnNxBYu/qkREouKNO46Fk";
    }

    /**
     * 随机生成密钥对
     */
    public static Map<String, String> genKeyPair() {
        //用于封装随机产生的公钥与私钥
        Map<String, String> keyMap = new HashMap<>();
        try {
            // KeyPairGenerator类用于生成公钥和私钥对，基于RSA算法生成对象
            KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");

            // 初始化密钥对生成器，密钥大小为96-1024位
            keyPairGen.initialize(1024, new SecureRandom());

            // 生成一个密钥对，保存在keyPair中
            KeyPair keyPair = keyPairGen.generateKeyPair();
            RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();   // 得到私钥
            RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();  // 得到公钥

            // 得到公钥字符串
            String publicKeyString = new String(Base64.encodeBase64(publicKey.getEncoded()));
            // 得到私钥字符串
            String privateKeyString = new String(Base64.encodeBase64((privateKey.getEncoded())));

            // 将公钥和私钥保存到Map
            keyMap.put(UpmpConstant.KEY_PAIR_MAP_PUBLIC_KEY, publicKeyString);  //0表示公钥
            keyMap.put(UpmpConstant.KEY_PAIR_MAP_PRIVATE_KEY, privateKeyString);  //1表示私钥
        } catch (Exception e) {
            log.info("生成公钥私钥异常：" + e.getMessage());
            return null;
        }

        return keyMap;
    }

    /**
     * RSA公钥加密
     *
     * @param str       需要加密的字符串
     * @param publicKey 公钥
     * @return 公钥加密后的内容
     */
    public static String encrypt(String str, String publicKey) {
        String outStr = null;
        try {
            //base64编码的公钥
            byte[] decoded = Base64.decodeBase64(publicKey);
            RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
            //RSA加密
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, pubKey);
            outStr = Base64.encodeBase64String(cipher.doFinal(str.getBytes("UTF-8")));
        } catch (Exception e) {
            log.info("使用公钥加密【" + str + "】异常：" + e.getMessage());
        }
        return outStr;
    }

    /**
     * RSA私钥解密
     *
     * @param str        加密字符串
     * @param privateKey 私钥
     * @return 私钥解密后的内容
     */
    public static String decrypt(String str, String privateKey) {
        String outStr = null;
        try {
            //64位解码加密后的字符串
            byte[] inputByte = Base64.decodeBase64(str.getBytes("UTF-8"));
            //base64编码的私钥
            byte[] decoded = Base64.decodeBase64(privateKey);
            RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
            //RSA解密
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, priKey);
            outStr = new String(cipher.doFinal(inputByte));
        } catch (Exception e) {
            log.info("使用私钥解密异常：" + e.getMessage());
        }
        return outStr;
    }
}
